/**
 * Created by JuntaoYi
 * Date 2020/3/31
 */
import axios from 'axios';
import { Component } from 'react';
import { message } from 'antd';
const NProgress = require('NProgress');

const instance = axios.create();

instance.interceptors.request.use(config => {
    config.withCredentials = true;
    return config;
});

instance.interceptors.response.use(response => {
    return response.data;
},err => {
    if (err.response.status === 504 || err.response.status === 404) {
        console.log("服务器被吃了⊙﹏⊙∥");
    } else if (err.response.status === 401) {
        console.log("登录信息失效⊙﹏⊙∥");
    } else if (err.response.status === 500) {
        console.log("服务器开小差了⊙﹏⊙∥");
    }
    return Promise.reject(err);
});

const request = (requestConfig) => {
    let url = requestConfig.url.path;
    if (requestConfig.params) {
        for (let key in requestConfig.params) {
            if (requestConfig.params.hasOwnProperty(key)) {
                url = url.replace('{' + key + '}', requestConfig.params[key])
            }
        }
    }
    let config = {
        url: url,
        method: requestConfig.url.method.toUpperCase()
    }
    if (requestConfig.url.method.toUpperCase() === 'GET') {
        config['params'] = requestConfig.data;
    } else {
        config['data'] = requestConfig.data;
    }
    // eslint-disable-next-line
    NProgress.start();
    instance.request(config).then(data => {
        NProgress.done();
        if (data.code === 200) {
            if (requestConfig.callback) {
                requestConfig.callback(data.result);
            }
            if(requestConfig.tip) {
                message.success(data.msg);
            }
        } else if (data.code === 1000) {
            error(requestConfig,data);
            message.error(data.msg);
        } else {
            if (requestConfig.tip) {
                message.error(data.msg);
            }
            error(requestConfig, data.msg);
        }
    }).catch(err => {
        // eslint-disable-next-line
        NProgress.done();
        message.error(err);
        error(requestConfig, err);
    })
}

function error(config, err, data) {
    if (config.error) {
        config.error(err, data);
    }
}

Component.prototype.request = request;
